package com.shty.wd.utils.module.IOTools;


import java.io.*;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class IOUtil { 

	public static String readDoc(File file) {
		try (FileInputStream fis = new FileInputStream(file)) {

			FileChannel inChanel = fis.getChannel();
			MappedByteBuffer buffer = inChanel.map(
					FileChannel.MapMode.READ_ONLY, 0, file.length());
			Charset charset = Charset.forName("utf-8");
			CharsetDecoder decoder = charset.newDecoder();
			CharBuffer charBuffer = decoder.decode(buffer);
			return charBuffer.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String loadSource(String path) {
		StringBuffer s = new StringBuffer();
		try (InputStream is = ClassLoader.getSystemResourceAsStream(path);
			 BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"))) {
			String line = "";
			while ((line = br.readLine()) != null) {
				line = line.trim().toLowerCase();
				s.append(line).append("|");
			}
			s = new StringBuffer(s.substring(0, s.length() - 1));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return s.toString();
	}
	//获取path文件夹下所有json数据，并以“,”隔开
	public static String readfromDir(String path) {
		File fileDir = new File(path);
		if (fileDir.isDirectory()) {
			StringBuffer content = new StringBuffer();
			content.append("[");
			for (File file : fileDir.listFiles()) {
				content.append(readDoc(file)).append(",");
			}
			if (content.lastIndexOf(",") > 1)
				content.substring(0, content.length() - 1);
			return content.append("]").toString();

		}
		return "";
	}
    public static void writeDoc(String result, String path) {
        try (FileOutputStream fo = new FileOutputStream(path);
             OutputStreamWriter os = new OutputStreamWriter(fo, "utf-8")) {
            os.write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
